<template>
    <div>
        <nav-bar>
            <template v-slot:default>
                购物车(<span style="color:red;">{{$store.state.cartCount}}</span>)
            </template>
        </nav-bar>
        <div class="cart-box">
            <div class="cart-body">
                <van-checkbox-group  ref="checkboxGroup" v-model="result" @change="groupChange">
                    <van-swipe-cell :right-width="50" v-for="item in list" :key="item.id" class="aa">
                        <div class="good-item">
                            <van-checkbox  class="cc" :name="item.id"/>
                            <div class="goods-card">
                                <div class="g_1">
                                    <img :src="item.goods.cover_url" alt="">
                                </div>
                                <div class="g_2">
                                    <p>{{item.goods.title}}</p>
                                    <p class="pp">{{item.goods.price+".00"}}</p>
                                </div>
                                <div class="g_3">
                                    <p>x{{item.goods.stock}}</p>
                                    <p>
                                        <van-stepper 
                                            integer :min="1" 
                                            :max="item.goods.stock" 
                                            :model-value="item.num" 
                                            :name="item.id" 
                                            async-change 
                                            @change="onChange"
                                            />    
                                    </p>
                                </div>
                            </div>
                        </div>
                        <template #right>
                            <van-button 
                                square
                                icon="delete"
                                type="danger"
                                class="delete-button"
                                @click="deleteGood(item.id)"
                                />
                        </template>
                    </van-swipe-cell>
                    
                </van-checkbox-group>
            </div>
            <van-submit-bar class="submit-all" :price="total*100" button-text="结算" @submit="onsubmit">
                <van-checkbox @click="allCheck" v-model:checked="checkAll">全选</van-checkbox>
            </van-submit-bar>
            <div class="empty" v-if="!list.length">
                <h3 style="margin-top:50px;">购物车空空</h3>
                <van-button round type="primary" block @click="goTo" style="margin-top:50px;">前往选购</van-button>
            </div>
        </div>
    </div>
</template>
<script>
import {ref,reactive,toRefs,onMounted,computed} from 'vue'
import NavBar from 'components/common/navbar/NavBar'
import {useRouter} from 'vue-router'
import {useStore} from 'vuex'
import {Toast} from 'vant'
// 获取购物车
import {getCart,deleteCartItem,checkedCart,modifyCart} from 'network/cart'
export default {
    name:'ShopCart',
    components:{
        NavBar
    },
    setup(){
        const router = useRouter();
        const store = useStore();

        // 数据模型
        const state = reactive({
            list:[],
            result:[], //购物车的id数组
            checkAll:true
        })
        //初始化购物车数据
        const init=()=>{
            Toast.loading({message:'加载中.....',forbidClick:true});
            // 获取购物车列表
            getCart('include=goods').then(res=>{    
                state.list = res.data;
                console.log(state.list);
                state.result = res.data.filter((n)=>n.is_checked == 1).map(item => item.id);
                console.log(state.result);
                Toast.clear();
            })
        }
        onMounted(()=>{
            init();
        })

        // 异步改变购物车数量
        const onChange = (value,detail)=>{
            Toast.loading({message:'修改中.....',forbidClick:true});
            // console.log(value);
            // console.log(detail.name);
            modifyCart(detail.name,{num:value}).then(res=>{
                // 将在onmount中的list中的num也要改
                state.list.forEach(item => {
                    if(item.id == detail.name){
                        item.num = value;
                    }
                })
                Toast.clear();
            })
        }
        // 复选框改变处理
        const groupChange = (result)=>{
            if(result.length == state.list.length){
                state.checkAll = true;
            }else{
                state.checkAll = false;
            }
            console.log(result);
            state.result = result;
            // 调用cart.js中的checkedCart方法，为了下次刷新的时候保存上次选中的
            checkedCart({cart_ids:result});
        }
        // 
        const allCheck = ()=>{
            if(!state.checkAll){
                state.result = state.list.map(item=>item.id)
                state.checkAll = true;
            }else{
                // 把所有id设置为空
                state.result = [];
                state.checkAll = false;
            }
        }


        // 前往购物车
        const goTo = ()=>{
            router.push({path:'/home'})
        }
        // 删除商品
        const deleteGood = (id)=>{
            deleteCartItem(id).then(res=>{
                init();  //重新初始化
                store.dispatch('updateCart'); //更新数据
            })
        }
        // 通过计算属性--总价
        const total = computed(()=>{
            let sum = 0;
            // 获取商品  每个商品包含这个item.id--过滤
            state.list.filter(item=> state.result.includes(item.id))
                .forEach(item => {
                    sum += (parseInt(item.num) * parseFloat(item.goods.price));
                })
            return sum;
        })
        // 创建订单
        const onsubmit = ()=>{
            if(state.result.length == 0){
                Toast.fail("请选择商品再进行结算！");
            }else{
                router.push({path:'/createorder'});
            }
        }

        return{
            ...toRefs(state),
            goTo,
            onChange,
            groupChange,
            allCheck,
            deleteGood,
            total,
            onsubmit
        }
    }
}
</script>
<style scoped lang="scss">
.delete-button{
    height: 150px;
}
.aa{
border-bottom: 1px solid lightblue;
}
    .submit-all{
        position: fixed;
        bottom: 50px;
        z-index: 6;
    }
    .cart-box{
        padding-top: 50px;
    }
    .goods-card{
        width: 92%;
        position: absolute;
        right: 0;
    }
    .cc{
        position: absolute;
        top:50px;
        left: 5px;
        z-index: 5;
    }
    .goods-card{
        display: flex;
        height: 150px;
        position: relative;
        .g_1{
            flex: 1;
            position: absolute;
            left: 40px;
            top: 20px;
            img{
                width: 100px;
                height: 100px;
            }
        }
        .g_2{
            flex: 1;
            position: absolute;
            left: 130px;
            top: 40px;
            p{
                font-size: 15px;
                padding: 8px 0px;
            }
            .pp{
                color: red;
            }
        }
        .g_3{
            flex: 1;
            position: absolute;
            left: 250px;
            top: 45px;
            text-align: right;
            p{
                font-size: 13px;
                padding: 5px 0px;
            }
        }
    }

</style>
